// 路由守卫
import router from '../index.ts'
import nprogress from 'nprogress'
import useUserStore from '@/store/modules/user.ts'
import 'nprogress/nprogress.css'

router.beforeEach(async (to, 
    // @ts-ignore
    from,
    next) => {
    nprogress.start();
    const useStoreUser = useUserStore()
    const token = useStoreUser.token
    const username = useStoreUser.username
    if (token) {
        if (to.path == '/login') {
            // 在登陆状态下访问login
            next({ path: '/' })
        }else {
            // 有用户名的情况下放行            
            if(username) {
                next()
            }else {
                try {
                    // 如果没有用户信息请求用户信息
                    await useStoreUser.useLoginInfo()
                    next({...to})
                } catch (error) {
                    // 用户token过期或者手动修改token
                    await useStoreUser.uselogOut()
                    next({path:'/login'})
                }
            }
        }
    }else {
        if(to.path == '/login') {
            next()
        }else {
            next({path:'/login'})
        }
    }
})
// 路由后置守卫
router.afterEach(()=>{
    nprogress.done();
})